package com.jojo.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.jojo.constant.StatusEnum;
import com.jojo.feign.StoreProdFeign;
import com.jojo.domain.Prod;
import com.jojo.exception.BusinessException;
import com.jojo.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jojo.mapper.IndexImgMapper;
import com.jojo.domain.IndexImg;
import com.jojo.service.IndexImgService;
@Service
public class IndexImgServiceImpl extends ServiceImpl<IndexImgMapper, IndexImg> implements IndexImgService{

    @Autowired
    private IndexImgMapper indexImgMapper;

    @Resource
    private StoreProdFeign storeProdFeign;

    @Override
    public Boolean saveIndexImg(IndexImg indexImg) {
        indexImg.setShopId(1L);
        indexImg.setCreateTime(new Date());
        //获取关联类型
        Integer type = indexImg.getType();
        if (-1 == type) {
            //说明没有关联
            indexImg.setProdId(null);
        }
        return indexImgMapper.insert(indexImg) > 0;
    }

    @Override
    public IndexImg queryIndexImgInfoById(Long indexImgId) {
        IndexImg indexImg = indexImgMapper.selectById(indexImgId);
        Integer type = indexImg.getType();
        //判断是否关联商品
        if (0 == type) {
            //说明关联商品
            //获取关联的商品id
            Long prodId = indexImg.getProdId();
            //根据商品id查询商品图片和名称  （这里需要远程调用）
            Result<List<Prod>> result = storeProdFeign.getProdListByIds(Arrays.asList(prodId));
            //判断是否正确
            if (StatusEnum.OPERATION_FAIL.getCode().equals(result.getCode())) {
                //操作失败
                throw new BusinessException(result.getMsg());
            }
            //获取数据
            List<Prod> prods = result.getData();
            //判断集合是否有值
            if (CollectionUtil.isNotEmpty(prods) && prods.size() != 0) {
                //获取商品对象
                Prod prod = prods.get(0);
                indexImg.setPic(prod.getPic());
                indexImg.setProdName(prod.getProdName());
            }
        }
        return indexImg;
    }

    @Override
    public Boolean modifyIndexImg(IndexImg indexImg) {
        return indexImgMapper.updateById(indexImg) > 0;
    }

    @Override
    public Boolean removeIndexImg(List<Long> ids) {
        return indexImgMapper.deleteBatchIds(ids) == ids.size();
    }
}
